<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class BWeChat extends BApp {

    protected $activeWXGroup;
    protected $activeMenuItem;
    protected $wxMenu = array();

    //this function will parse wxData and set active space, active app and active operation
    public static function setContext($wxData = null, $data = NULL) {
        
    }

    /**
     * this function use to get all menus for weixin menu
     * @param type $data
     * @param type $data
     */
    public function getWXMenu($data = NULL, $data = NULL) {
        
    }

    public function setWXMenu($wxMenu, $data = NULL) {
        
    }

    public function getActiveMenuItem($data = NULL) {
        
    }

    public function setActiveMenuItem($activeMenuItemData, $data = NULL) {
        
    }

    public function getActiveWXGroup($data = NULL) {
        
    }

    public function setActiveWXGroup($wxGroup, $data = NULL) {
        
    }

    public function updateWXMenu($wxMenu = null, $data = NULL) {
        
    }

    public function run($data = NULL) {
        parent::run($data);
    }

    public function runSetupWeChat($data = NULL) {
        $sender = Blyn::app()->getUIManager()->getSenderControl();
        $updateControl = Blyn::app()->getUIManager()->getUpdateControl();

        if ($sender instanceof BUIControl && $updateControl instanceof BUIControl) {
//            if ($sender->isAjaxLinkClicked('saveMenu')) {
//                
//                 $wxMenuControl = new BUIWXMenu($operation);
//                 $children = $wxMenuControl->getChildren();
//                if (!empty($_POST)) {
//                    $parentid = $_POST[$parentid];
//                    $menu_name = $_POST[$menu_name];
//                if($parentid>=2){
//                    if($parentid==2){
//                   $menu1 = $wxMenuControl->getChild('重庆商社');
//                   $menu1->addChild($menu_name);  
//                    }
//                   if($parentid==3)
//                   {
//                   $menu1 = $wxMenuControl->getChild('商社导航');
//                   $menu1->addChild('$menu_name');
//                   }
//                    if($parentid==9)
//                   {
//                   $menu1 = $wxMenuControl->getChild('商社乐购');
//                   $menu1->addChild('$menu_name');
//                   }
//                    if($parentid==14)
//                   {
//                   $menu1 = $wxMenuControl->getChild('我的商社');
//                   $menu1->addChild('$menu_name');
//                   }
//                   
//                   
//                }
//                else
//                {
//                    echo '添加失败';
//                    
//                }    
//            }
//            }

            if ($sender->isAjaxLinkClicked('Show Menu Designer')) {
                $model = new BWXMenuFormModel();
                if (isset($_POST['BWXMenuFormModel'])) {
                    $model->attributes = $_POST['BWXMenuFormModel'];
                }
                $operationId = $model->operationId;
                if ($operationId > 0) {
                    $operation = new BOperation($operationId);
                    Blyn::app()->getActiveOperation()->addContextVariable('workingOperationId', $operationId);
                }
                $activeSpace = Blyn::app()->getActiveSpace();

                if ($operation instanceof BEntity) {
                    $wxMenuControl = new BUIWXMenu($operation);
                    if ($operation->getName() == 'followEvent') {
                        $children = $wxMenuControl->getChildren();
                        if (empty($children)) { // inital menus
//                        if (empty($children) && $activeSpace->getName() == '重庆商社') { // inital menus       
                            $menu1 = $wxMenuControl->getChild('商社导航');
                            if (!$menu1 instanceof BUIMenu)
                                $menu1 = $wxMenuControl->addChild('商社导航');
                            $menu1->addChild('酒店');
                            $menu1->addChild('汽车');
                            $menu1->addChild('百货');
                            $menu1->addChild('电器');
                            $menu1->addChild('商品促销');

                            $menu1 = $wxMenuControl->addChild('商社乐购');
                            $menu1->addChild('活动分享');
                            $menu1->addChild('微抢购');
                            $menu1->addChild('商社活动');
                            $menu1->addChild('品牌优惠');
                            $menu1->addChild('活动分享');

                            $menu1 = $wxMenuControl->addChild('我的商社');
                            $menu1->addChild('电子会员卡');
                            $menu1->addChild('我的订单');
                            $menu1->addChild('投票管理'); //我的关注
                            $menu1->addChild('我的抽奖');
                            $menu1->addChild('我的维权');
                        }
                        //$menu1 = $wxMenuControl->getChild('商社导航');
                    }
                    $newAppId = $model->applicationId;
                    $newAppSecret = $model->appSecret;
                    if ($newAppId == "" || $newAppSecret == "") {
                        echo '<script language="javascript">';
                        echo 'alert("AppId或AppSecret不能为空！");';
                        echo '</script>';
                    } else {
                        Blyn::app()->getActiveSpace()->addAttribute('wechat_appid', $newAppId);
                        Blyn::app()->getActiveSpace()->addAttribute('wechat_appsecret', $newAppSecret);
                        $updateControl->addRenderView('menuDesignContainer', 'menuDesignContainer', array(
                            'menuControl' => $wxMenuControl,
                            'operation' => $operation
                        ));
                    }
                }
            }
            if ($sender->isAjaxLinkClicked('配置微信信息')) {
                $model = new BWXMenuFormModel();
                if (isset($_POST['BWXMenuFormModel'])) {
                    $model->attributes = $_POST['BWXMenuFormModel'];
                }
                $operationId = $model->operationId;
                if ($operationId > 0) {
                    $operation = new BOperation($operationId);
                    Blyn::app()->getActiveOperation()->addContextVariable('workingOperationId', $operationId);
                }
                $activeSpace = Blyn::app()->getActiveSpace();
                $newAppId = $model->applicationId;
                $newAppSecret = $model->appSecret;
                if ($newAppId == "" || $newAppSecret == "") {
                    echo '<script language="javascript">';
                    echo 'alert("AppId或AppSecret不能为空！");';
                    echo '</script>';
                } else {
                    Blyn::app()->getActiveSpace()->addAttribute('wechat_appid', $newAppId);
                    Blyn::app()->getActiveSpace()->addAttribute('wechat_appsecret', $newAppSecret);
                    echo '<script language="javascript">';
                    echo 'alert("配置成功！");';
                    echo '</script>';
                    //$updateControl->addRenderView('manageMenu', 'manageMenu');
                }
            }
            if ($sender->isAjaxLinkClicked('releaseMenu')) {
                $Appid = Blyn::app()->getActiveSpace()->getAttribute('wechat_appid')->getValue();
                $Appsecret = Blyn::app()->getActiveSpace()->getAttribute('wechat_appsecret')->getValue();
                $urlPrefix = 'http://www.billyn.net/wechat/local.php?id=';
                $urlPrefix .= $Appid;
                $urlPrefix .='&scr=';
                $urlPrefix .=$Appsecret;
                $urlPrefix .='&to=';
//                $urlPrefix .= '&redirect_uri=http://hamshun.sinaapp.com/97_2.php?T=';
//                $urlSurfix = '&response_type=code&scope=snsapi_base&state=1#wechat_redirect';
                $activeSpace = Blyn::app()->getActiveSpace();
                $wxMenuControl = new BUIWXMenu($activeSpace);
                $menuRoot = $wxMenuControl->getRoot();
                $firstLevelMenus = $menuRoot->getChildren();
                $json = '{"button":[';
                foreach ($firstLevelMenus as $firstLevelMenu) { 
                    $arr = explode('&%@', $firstLevelMenu->getValue());
                    $MenuName = $arr[0];
                    $myUrl = $arr[2];
                    $secondLevelMenus = $firstLevelMenu->getChildren();
                    if(!$secondLevelMenus){
                        $json .= '{
                               "type":"view",
                               "name":"'.$MenuName.'",
                               "url":"'.$urlPrefix .'http://www.billyn.net'.$myUrl.'"
                            },';
                    }  else {
                        $json .= '{"name":"'.$MenuName.'","sub_button":[';
                        foreach ($secondLevelMenus as $secondLevelMenu) {
                            $arr = explode('&%@', $secondLevelMenu->getValue());
                            $MenuName = $arr[0];
                            $myUrl = $arr[2];
                            $json .= '{
                                       "type":"view",
                                       "name":"'.$MenuName.'",
                                       "url":"'.$urlPrefix.'http://www.billyn.net'.$myUrl.'"
                                    },';

                        }
                         $json .= ']},';
                    }

                }
                $json .= ']}';
                $json = str_replace('},]', '}]', $json);
                //在获取到微信菜单数据后
                $menu = new BWeChatClass($Appid, $Appsecret);
                $errmsg = $menu->create_menu($json);
                    $errmsg["errmsg"] =="ok";
                if ($errmsg["errmsg"] == "ok") {
                    echo '<script language="javascript">';
                    echo 'alert("发布成功！");';
                    echo '</script>';
                } else {
                    echo '<script language="javascript">';
                    echo 'alert("发布失败！");';
                    echo '</script>';
                }
                 $updateControl->addRenderView('menuDesignContainer', 'menuDesignContainer');
            }
            if ($sender->isAjaxLinkClicked('saveMenu')) {
                $operationId = Blyn::app()->getActiveOperation()->getContextVariable('workingOperationId');
                $operation = NULL;
                if ($operationId > 0)
                    $operation = new BOperation($operationId);
                $activeSpace = Blyn::app()->getActiveSpace();
                if ($operation instanceof BOperation) {
                    $wxMenuControl = new BUIWXMenu($operation);
                    if (!empty($_POST)) {
                        $menuName = isset($_POST['name']) ? $_POST['name'] : NULL;
                        $parentId = isset($_POST['parentId']) ? $_POST['parentId'] : NULL;
                        $displayName = isset($_POST['displayName']) ? $_POST['displayName'] : NULL;

                        if (!is_null($parentId)) {
                            if ($parentId == 0) {//root node
                                $menu = $wxMenuControl->getRoot();
                                $menu->addChild(array('name' => $menuName, 'value' => $displayName));
                            }
                            if ($parentId > 0) {
                                $menu = $wxMenuControl->getMenuById($parentId);
                                $menu->addChild(array('name' => $menuName, 'value' => $displayName));
                            }
                        }
                    }
                    $updateControl->addRenderView('menuDesignContainer', 'menuDesignContainer', array('menuControl' => $wxMenuControl, 'operation' => $operation));
                }
            }
            
            if ($sender->isAjaxLinkClicked('saveMenu_1')) {
                if(isset($_POST['button'])) {
                    $buttons = $_POST['button'];
                    $activeSpace = Blyn::app()->getActiveSpace();
                    $wxMenuControl = new BUIWXMenu($activeSpace);
                    $menuRoot = $wxMenuControl->getRoot();
                    foreach ($buttons as $key1 => $button) {
                        $displayName = $button['name'];
                        $url = null;
                        if(!isset($button['sub_button'])) 
                            $url = $button['url'];
                        $name = 'wx0-'.$key1;
                        $value = isset($button['sub_button']) ? '' : $button['operationId'];
                        $firstLevelMenu = $menuRoot->addChild(array('name' => $name,'value' => $displayName.'&%@'.$value.'&%@'.$url));
                        if(isset($button['sub_button'])) {
                            foreach ($button['sub_button'] as $key2 => $subButton) {
                                $displayName = $subButton['name'];
                                $url = $subButton['url'];
                                $name = 'wx0-'.$key1.'-'.$key2;
                                $value = isset($subButton['sub_button']) ? '' : $subButton['operationId'];
                                $firstLevelMenu->addChild(array('name' => $name, 'value' => $displayName.'&%@'.$value.'&%@'.$url));
                            }
                        }
                    }
                }
                $updateControl->addRenderView('menuDesignContainer', 'menuDesignContainer');
            }
            
            if ($sender->isAjaxLinkClicked('deleteMenu')) {
                $operationId = Blyn::app()->getActiveOperation()->getContextVariable('workingOperationId');
                $operation = NULL;
                if ($operationId > 0)
                    $operation = new BOperation($operationId);
                $activeSpace = Blyn::app()->getActiveSpace();
                if ($operation instanceof BOperation) {
                    $wxMenuControl = new BUIWXMenu($operation);
                    if (!empty($_POST)) {
                        $menuId = isset($_POST['id']) ? $_POST['id'] : NULL;
                        $menuParentId = isset($_POST['parentId']) ? $_POST['parentId'] : NULL;
                        if (!is_null($menuId)) {
                                $menu = $wxMenuControl->getMenuById($menuId);
//                                $name = $menu->name;
                                $menu->removeChidren($menu);
                        }
                    }
                    $updateControl->addRenderView('menuDesignContainer', 'menuDesignContainer', array('menuControl' => $wxMenuControl, 'operation' => $operation));
                }
            }
            if($sender->isAjaxLinkClicked('WeChatQy')){
                 $updateControl->addRenderView('showWeChatQy', 'WeChatQy_index');
            }
            if($sender->isAjaxLinkClicked('getHelp')){
                $updateControl->addRenderView('getHelp_appid','getHelp_appid');
            }
            if($sender->isAjaxLinkClicked('addWeChatQyApp')){
                 $eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
                 $updateControl->addRenderView('addWeChatQyApp', 'event_add', array('eventId' => $eventId));
            }
            if($sender->isAjaxLinkClicked('showEventList')){
                $updateControl->addRenderView('showWeChatQy', 'WeChatQy_index');
            }
            if($sender->isAjaxLinkClicked('getHelpAddWeChatQy')){
                $updateControl->addRenderView('getHelpAddWeChatQy', 'getHelp_AddWeChatQyApp');
            }
            if($sender->isAjaxLinkClicked('getHelp_CorpID')){
                $updateControl->addRenderView('getHelp_CorpID', 'getHelp_CorpID');
            }
//            if ($sender->isAjaxLinkClicked('sendMesaage')) {
//                if (!empty($_POST)) {
//                    $msg = isset($_POST['msg']) ? $_POST['msg'] : NULL;
//                    $demoopenid = isset($_POST['openid']) ? $_POST['openid'] : NULL;
//
//                    $wechat = new BWeChatClass("wxd33a8d04590d6e58", "76668778e8c8debba1cdc28ae0df8a20");
//                    $errmsg = $wechat->send_custom_message($demoopenid, "text", $msg);
//                    if ($errmsg["errmsg"] == "ok") {
//                        echo '<script language="javascript">';
//                        echo 'alert("ok！");';
//                        echo '</script>';
//                    } else {
//                        echo '<script language="javascript">';
//                        echo 'alert("error！");';
//                        echo '</script>';
//                    }
//                }
//            }
        }
    }

    public function runManageWeChatUsers($operation = NULL, $data = NULL) {
        $sender = Blyn::app()->getUIManager()->getSenderControl();
        $updateControl = Blyn::app()->getUIManager()->getUpdateControl();
        if ($sender->isAjaxLinkClicked('sendMesaage')) {
            $Appid = Blyn::app()->getActiveSpace()->getAttribute('wechat_appid')->getValue();
            $Appsecret = Blyn::app()->getActiveSpace()->getAttribute('wechat_appsecret')->getValue();
            if (!empty($_POST)) {
                $msg = isset($_POST['msg']) ? $_POST['msg'] : NULL;
                $demoopenid = isset($_POST['openid']) ? $_POST['openid'] : NULL;
                $wechat = new BWeChatClass($Appid, $Appsecret);
                $errmsg = $wechat->send_custom_message($demoopenid, "text", $msg);
//                    if ($errmsg["errmsg"] == "ok") {
//                        return "success";
//                    } else {
//                        return "error";
//                    }
            }
        }
        if ($sender->isAjaxLinkClicked('sendMesaageToShareUsers')) {
            if (!empty($_POST)) {
                $msg = isset($_POST['msg']) ? $_POST['msg'] : NULL;
                $demoopenid = isset($_POST['openid']) ? $_POST['openid'] : NULL;
                $Appid = isset($_POST['wxAppId']) ? $_POST['wxAppId'] : NULL;
                $Appsecret = isset($_POST['wxAppSecret']) ? $_POST['wxAppSecret'] : NULL;
                $wechat = new BWeChatClass($Appid, $Appsecret);
                $errmsg = $wechat->send_custom_message($demoopenid, "text", $msg);
//                    if ($errmsg["errmsg"] == "ok") {
//                        return "success";
//                    } else {
//                        return "error";
//                    }
            }
        }
        if ($sender->isAjaxLinkClicked('sendGroupMessage')) {
            if (!empty($_POST)) {
                $msg = isset($_POST['msg']) ? $_POST['msg'] : NULL;
                $demogroupid = isset($_POST['groupid']) ? $_POST['groupid'] : NULL;

                $wechat = new BWeChatClass("wxd33a8d04590d6e58", "76668778e8c8debba1cdc28ae0df8a20");
                $errmsg = $wechat->mass_send_group($demogroupid, "text", $msg);
//                    $errmsg = $wechat->send_custom_message($demoopenid, "text", $msg);
//                    if ($errmsg["errmsg"] == "ok") {
//                        return "success";
//                    } else {
//                        return "error";
//                    }
            }
        }
//        if ($sender->isAjaxLinkClicked('sendSingleMessage')) {
//            $nickname = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('userName');
//            $userOpenid = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('userOpenid');
//            $updateControl->addRenderView('sendSingleMessage', 'sendSingleMessage', array('nick_name' => $nickname, 'openid' => $userOpenid));
//        }
//        if ($sender->isAjaxLinkClicked('show Wechat users')) {
//            $space = Blyn::app()->getActiveSpace();
//            if ($space->getAttribute('wechat_appid') == FALSE) {
////            $wxAppId = $space->getAttribute('wechat_appid')->getValue();
////            $wxAppSecret = $space->getAttribute('wechat_appsecret')->getValue();
////            if($wxAppId == "" ||$wxAppSecret ==""){
//                echo '<script language="javascript">';
//                echo 'alert("AppId与AppSecret不能为空，请于setupWeChat填写信息！");';
//                echo '</script>';
//            } elseif ($space->getAttribute('wechat_openid0') == FALSE) {
//                echo '<script language="javascript">';
//                echo 'alert("粉丝为空，请先更新粉丝！");';
//                echo '</script>';
//            } else {
//                $updateControl->addRenderView('showWechatUsers', 'showWechatUsers');
//            }
//        }

        if ($sender->isAjaxLinkClicked('Update Wechat Users')) {
            $space = Blyn::app()->getActiveSpace();
            if ($space->getAttribute('wechat_appid') == FALSE) {
//            $wxAppId = $space->getAttribute('wechat_appid')->getValue();
//            $wxAppSecret = $space->getAttribute('wechat_appsecret')->getValue();
//            if($wxAppId == "" ||$wxAppSecret ==""){
                echo '<script language="javascript">';
                echo 'alert("AppId与AppSecret不能为空，请于setupWeChat填写信息！");';
                echo '</script>';
            } else {
                $wxAppId = $space->getAttribute('wechat_appid')->getValue();
                $wxAppSecret = $space->getAttribute('wechat_appsecret')->getValue();
                $wechat = new BWeChatClass($wxAppId, $wxAppSecret);
                $userList = $wechat->get_user_list();
                $total = $userList["total"];
                $userOpenidArray = $userList["data"]["openid"];
//                $i = 0;
//                foreach ($userOpenidArray as $openid) {
//                    if ($i < 30) {
//                        $space->addAttribute('wechat_openid' . $i, $openid);
//                        $i++;
//                    } else {
//                        break;
//                    }
//                }
                Blyn::app()->getActiveSpace()->addAttribute('wechat_openid', $userOpenidArray);
                echo '<script language="javascript">';
                echo 'alert("更新完成！");';
                echo '</script>';
            }
        }
    }

    public function getOperationList($data = NULL) {
        $apps = Blyn::app()->getActiveSpace()->getApps();

        $opList = array();

        foreach ($apps as $app) {
            if ($app instanceof BApp) {
                $ops = $app->getOperations();
                foreach ($ops as $op) {
                    $name = $app->getName() . ":";
                    if ($op instanceof BOperation) {
                        $name .= $op->getName();
                        $opList[$op->getId()] = $name;
                    }
                }
            }
        }

        return $opList;
    }

}

?>
